#include "stockindao.h"

StockInDAO::StockInDAO(Database *db) : m_db(db) {}

bool StockInDAO::addStockInRecord(int productId, int quantity, double price,
                                 const QString &supplier, int operatorId, const QString &note)
{
    QString query = "INSERT INTO stock_in (product_id, in_quantity, in_price, supplier, operator_id, note) "
                   "VALUES (?, ?, ?, ?, ?, ?)";
    return m_db->execute(query, {productId, quantity, price, supplier, operatorId, note});
}

bool StockInDAO::beginTransaction()
{
    return m_db->beginTransaction();
}

bool StockInDAO::commitTransaction()
{
    return m_db->commitTransaction();
}

bool StockInDAO::rollbackTransaction()
{
    return m_db->rollbackTransaction();
}

// 获取所有入库记录（用于统计页面）
QVector<QMap<QString, QVariant>> StockInDAO::getAllStockInRecords()
{
    QString query = "SELECT s.in_id, s.product_id, p.product_name, s.in_quantity, "
                   "s.in_price, s.in_time, s.operator_id, u.real_name as operator_name, "
                   "s.supplier, s.note, c.category_name "
                   "FROM stock_in s "
                   "LEFT JOIN product p ON s.product_id = p.product_id "
                   "LEFT JOIN user u ON s.operator_id = u.user_id "
                   "LEFT JOIN category c ON p.category_id = c.category_id "
                   "ORDER BY s.in_time DESC";
    
    return m_db->query(query);
}

// 根据条件查询入库记录
QVector<QMap<QString, QVariant>> StockInDAO::getStockInRecordsByCondition(
    const QString &startDate, const QString &endDate,
    int productId, const QString &supplier)
{
    QString query = "SELECT s.in_id, s.product_id, p.product_name, s.in_quantity, "
                   "s.in_price, s.in_time, s.operator_id, u.real_name as operator_name, "
                   "s.supplier, s.note, c.category_name "
                   "FROM stock_in s "
                   "LEFT JOIN product p ON s.product_id = p.product_id "
                   "LEFT JOIN user u ON s.operator_id = u.user_id "
                   "LEFT JOIN category c ON p.category_id = c.category_id "
                   "WHERE 1=1";
    
    QVector<QVariant> params;
    
    if (!startDate.isEmpty()) {
        query += " AND s.in_time >= ?";
        params.append(startDate);
    }
    
    if (!endDate.isEmpty()) {
        query += " AND s.in_time <= ?";
        params.append(endDate);
    }
    
    if (productId > 0) {
        query += " AND s.product_id = ?";
        params.append(productId);
    }
    
    if (!supplier.isEmpty()) {
        query += " AND s.supplier LIKE ?";
        params.append("%" + supplier + "%");
    }
    
    query += " ORDER BY s.in_time DESC";
    
    return m_db->query(query, params);
}
